import ReceivepigApi from '../../../common/api/cbs/receivepig.api.js';
import doT from '../../../../vendor/template/doT.js';
import { DictionaryType, requestDict } from "../../../common/dictionary/dictionary-type.js";
import { uploadFile, requestFilePath, publicFileDraw, sliceFileName } from "../../../common/api/file-request.js";
import { Select2Info, Select2Page } from "../../../common/serve-request.js";
import { locationService } from '../../../common/locationService.js';

let getEntryInfo = [], _vm, curAllorg, addressindex = 0, editintentionCity, editintentionArr
const addsaleTemplate = doT.template($('#addsaleorders-template').text());
const curOrg = JSON.parse(Utils.GetSessionStorage('SNLoginUserInfo'));
(function (window, document, $) {
    $(function () {
        _vm = new Vue({
            el: "#addsaleorders-form",
            data() {
                return {
                    bizDate: moment(new Date()).format('YYYY-MM-DD'),
                    supplierId: "",
                    supplierName: "",
                    supplierNumCode: "",
                    farmOrgUnitName: "",
                    suppBreedBatchName: "",
                    totalCount: "",
                    totalWeight: "",
                    totalPrice: "",
                    totalSuupLossCount: "",
                    totalBuyLossCount: "",
                    entryDays: "",
                    shipAddress: "",
                    shipRegion: "",
                    fiOrgUnitId: "",
                    fiOrgUnitName: "",
                    serviceDepartmentId: "",
                    serviceDepartmentName: "",
                    remark: "",
                    entries: [],
                    newtotalCount: "",
                    selctbreedBatchName: "",
                    selctFarmName: ""
                }
            },
            mounted() {
                let url = location.href
                let params = {} // url参数
                for (let key of (new URL(url)).searchParams.entries()) {
                    key[1] ? params[key[0]] = key[1] : ''
                }
                let ids = Utils.GetSessionStorage("ids")
                if (params.id || ids) {
                    document.title = '接苗单 - 编辑'
                }
            },
        });
        $('body').attr('data-weui-theme', 'light'); //强制光明模式
        clickFun()
        _initCommand()
        _initcityPicker()
    });

    // 初始化数据
    const _initCommand = async () => {
        // 选择日期
        $('#search-date').on('click', function () {
            pick();
        });
        // 初始化公司
        let curAllorg = await ReceivepigApi.getOrgsList()
        let companyInfo = await ReceivepigApi.queryBaseOrgunitList('ooca', 10, '226')
        $('#fiOrgUnit').select2({
            placeholder: '请选择公司...', //默认文字提示
            language: "zh-CN",//汉化
            allowClear: true,//允许清空
            data: companyInfo.map(item => {
                return {
                    id: item.id,
                    text: `${item.name}(${item.numCode})`,
                    name: item.name
                }
            }),
        });
        $('#fiOrgUnit').setSelectValue()

        // 选择公司
        $('#fiOrgUnit').on("select2:select", async function () {
            let saleOrgsinfo = cutstr($('#select2-fiOrgUnit-container').text(), 22)
            $('#select2-fiOrgUnit-container').text(saleOrgsinfo.slice(1))
            _vm.fiOrgUnitId = $('#fiOrgUnit').select2('data')[0]?.id
            _vm.fiOrgUnitName = $('#fiOrgUnit').select2('data')[0]?.name
            await _serviceDepartment(_vm.fiOrgUnitId, {});
        })
        // 选择农场
        $('#farmOrg').on("select2:select", function () {
            let saleOrgsinfo = cutstr($('#select2-farmOrg-container').text(), 22)
            $('#select2-farmOrg-container').text(saleOrgsinfo.slice(1))
            _vm.serviceDepartmentId = $('#farmOrg').select2('data')[0]?.id
            _vm.serviceDepartmentName = $('#farmOrg').select2('data')[0]?.name
        })

        // 初始化供应商
        $('#supplier').select2({
            allowClear: true,
            language: "zh-CN",
            placeholder: '请选择供应商...', //默认文字提示
            ajax: {
                url: `${Utils.CurDomain.MasterDataUrl}/yysuppliers/by/q`,
                dataType: 'json',
                type: 'GET',
                beforeSend: Utils.AjaxBeforeSend,
                data: function (params) {
                    return {
                        SearchInfo: params.term,
                        PageSize: 10,
                        PageIndex: (params.page || 1) - 1
                    };
                },
                processResults: function (data, params) {
                    params.page = params.page || 1;
                    let _data = data.data.items.map(item => {
                        item.text = `${item.name}`;
                        return item;
                    });
                    return {
                        results: _data,// 后台返回的数据集
                        pagination: {
                            more: params.page < data.data.totalPages// 总页数为10，那么1-9页的时候都可以下拉刷新
                        }
                    };
                },
                minimumInputLength: 1,
            }
        });
        $('#supplier').setSelectValue();
        // 选择供应商
        $('#supplier').on("select2:select", function () {
            _vm.supplierId = $('#supplier').select2('data')[0]?.id
            _vm.supplierName = $('#supplier').select2('data')[0]?.name
            _vm.supplierNumCode = $('#supplier').select2('data')[0]?.numCode
            let org = $('#supplier').select2('data')[0].org;
            if (Utils.IsNotNull(org?.id)) {
                _queryFarmName(org?.id);
                $('#selctFarm,#selctbreedBatch').css('display', 'block')
                $('#inputFarm,#inputbreedBatch').css('display', 'none')
                _vm.suppBreedBatchName = ''
                _vm.farmOrgUnitName = ''

            } else {
                $('#selctFarm,#selctbreedBatch').css('display', 'none')
                $('#inputFarm,#inputbreedBatch').css('display', 'block')

            }
        })
        $(`#breedBatch`).empty().select2({ placeholder: `请选择供方批次...`, });

        // 选择供方猪场
        $('#farmName').on("select2:select", function () {
            _initbreedBatch()
        })

        $('#supplier').on('change', function () {
            let saleOrgsinfo = cutstr($('#select2-supplier-container').text(), 20)
            $('#select2-supplier-container').text(saleOrgsinfo.slice(1))
        })

        // 编辑
        let ids = getUrlKey("id")
        if (Utils.IsNotNull(ids)) {
            $("#informationSubmit").text("保存");
            await ReceivepigApi.getReceivePigBill(ids).then(res => {
                res.selctbreedBatchName = res.suppBreedBatchName
                res.selctFarmName = res.farmOrgUnitName
                Utils.SetRouterState('deliverDatas', res)
                JSON.stringify(Utils.SetSessionStorage("ids", ids))
                res.entreis.forEach((item, index) => {
                    item.seq = index;
                    item.farmerId = item.farmersId;
                    item.farmerName = item.farmersName
                })
                JSON.stringify(Utils.SetSessionStorage("getEntryInfo", res.entreis))
            });
        }

        // 获取主表数据
        let getMainInfo = JSON.parse(Utils.GetSessionStorage("deliverDatas"))
        if (Utils.IsNotNull(getMainInfo)) {
            let { fiOrgUnitId, fiOrgUnitName, serviceDepartmentId, serviceDepartmentName, supplierId, supplierName } = getMainInfo
            $('#fiOrgUnit').setSelectValue(fiOrgUnitId, fiOrgUnitName);
            $('#farmOrg').setSelectValue(serviceDepartmentId, serviceDepartmentName);
            let farmInfo = {
                'serviceDepartmentId': serviceDepartmentId,
                'serviceDepartmentName': serviceDepartmentName
            }
            await _serviceDepartment(fiOrgUnitId, farmInfo);
            $('#supplier').setSelectValue(supplierId, supplierName);
            const propertiesToCopy = [
                'bizDate', 'supplierId', 'supplierName', 'supplierNumCode', 'farmOrgUnitName',
                'suppBreedBatchName', 'totalCount', 'totalWeight', 'totalPrice', 'totalSuupLossCount',
                'totalBuyLossCount', 'entryDays', 'shipAddress', 'shipRegion', 'fiOrgUnitId',
                'fiOrgUnitName', 'serviceDepartmentId', 'serviceDepartmentName', 'remark', 'selctbreedBatchName', 'selctFarmName'
            ];
            propertiesToCopy.reduce((obj, prop) => {
                _vm[prop] = getMainInfo[prop];
            }, {});
            _vm.bizDate = moment(getMainInfo?.bizDate).format('YYYY-MM-DD')
            if (Utils.IsNotNull(getMainInfo.shipRegion)) {
                let shipRegion = getMainInfo.shipRegion.split('|')[1].split(';');
                if (Utils.IsNotNull(shipRegion[3])) {
                    let shipAddress = `${shipRegion[0]}-${shipRegion[1]}-${shipRegion[2]}-${shipRegion[3]}`
                    $('#intentionCity').val(shipAddress)
                }
                else {
                    let shipAddress = `${shipRegion[0]}-${shipRegion[1]}-${shipRegion[2]}`
                    $('#intentionCity').val(shipAddress)
                }
            }
            if (Utils.IsNotNull(_vm.selctFarmName)) {
                let supplierInfo = await ReceivepigApi.getSupplier(_vm.supplierNumCode);
                let org = supplierInfo.items[0]?.org;
                if (Utils.IsNotNull(org.id)) {
                    _queryFarmName(org?.id, _vm.selctFarmName);
                    $('#selctFarm,#selctbreedBatch').css('display', 'block')
                    $('#inputFarm,#inputbreedBatch').css('display', 'none')
                    _initbreedBatch(_vm.selctbreedBatchName)
                } else {
                    $('#selctFarm,#selctbreedBatch').css('display', 'none')
                    $('#inputFarm,#inputbreedBatch').css('display', 'block')
                }
            }
        }
        else {
            // 新增 带出默认组织
            let curOrgInfo = curAllorg.filter(item => item.oId == curOrg.coui)
            if (curOrgInfo[0]?.aoType == 10) {
                $('#fiOrgUnit').setSelectValue(curOrgInfo[0]?.oId, curOrgInfo[0]?.oName);
                _vm.fiOrgUnitId = curOrgInfo[0]?.oId
                _vm.fiOrgUnitName = curOrgInfo[0]?.oName
                if (Utils.IsNotNull(_vm.serviceDepartmentId)) {
                    let farmInfo = {
                        'serviceDepartmentId': _vm.serviceDepartmentId,
                        'serviceDepartmentName': _vm.serviceDepartmentName
                    }
                    await _serviceDepartment(curOrgInfo[0]?.oId, farmInfo);

                }
                else {
                    await _serviceDepartment(curOrgInfo[0]?.oId, {});
                }
            }
            else if (curOrgInfo[0]?.aoType == 1) {
                let parentArr = getAllParend(curOrgInfo[0].poId, curAllorg)
                let parentOrg = parentArr.filter(item => {
                    return item.aoType == 10 && item.tags == 226
                })
                if (Utils.IsNotNull(parentOrg)) {
                    $('#fiOrgUnit').setSelectValue(parentOrg[0]?.oId, parentOrg[0]?.oName);
                    _vm.fiOrgUnitId = parentOrg[0]?.oId
                    _vm.fiOrgUnitName = parentOrg[0]?.oName
                    let farmInfo = {
                        'serviceDepartmentId': curOrgInfo[0]?.oId,
                        'serviceDepartmentName': curOrgInfo[0]?.oName
                    }
                    await _serviceDepartment(parentOrg[0]?.oId, farmInfo);
                }
                else {
                    $("#farmOrg").select2({
                        placeholder: '请选择服务部...',//默认文字提示
                        language: "zh-CN",//汉化
                        allowClear: true,
                    });
                }
            }
        }


        // 获取分录信息
        getEntryInfo = JSON.parse(Utils.GetSessionStorage("getEntryInfo"))
        if (Utils.IsNotNull(getEntryInfo)) {
            let type = await requestDict(DictionaryType.PIG_VARIETIES)
            getEntryInfo = getEntryInfo.map(item => {
                let pigBreedStr = type.data.find(itm => itm.value == item.pigBreed)?.displayName || ""
                return { ...item, pigBreedStr }
            });
            $('#salesEntry').empty().append(addsaleTemplate(getEntryInfo));

            let _netWeight = [], _count = [], _buyLossCount = [];
            $.each(getEntryInfo, function (i, v) {
                _netWeight.push(Number(v.netWeight));
                _count.push(parseInt(v.count));
                _buyLossCount.push(parseInt(v.buyLossCount));
            });
            let netWeight = eval(_netWeight?.join('+'));
            let count = eval(_count?.join('+'));
            let buyLossCount = eval(_buyLossCount?.join('+'));
            _vm.totalWeight = netWeight || 0
            _vm.totalCount = count || 0
            _vm.totalBuyLossCount = buyLossCount || 0
            _vm.newtotalCount = count + buyLossCount || 0
        }
    }
    const _initbreedBatch = (selctbreedBatchName) => {
        Select2Page($(`#breedBatch`), `${Utils.CurDomain.BaseCfgUrl}/breedbatchs/rlist`, (params) => {
            let farmOrgId = $(`#farmName`).select2('data')[0]?.id
            return JSON.stringify({
                farmOrgId,
                tags: '',
                name: params.term,
                sort: '',
                isEnd: false,
                pageSize: 20,
                pageIndex: (params.page || 1) - 1
            })
        }, "POST", {
            placeholder: '请选择供方批次...', //默认文字提示
            tags: true,
            width: '100%',
            //allowClear: true,//允许清空
            templateResult: function (res) {
                return `${res.name == undefined ? res.text : res.name}`;
            }
        });
        $('#breedBatch').setSelectValue(selctbreedBatchName, selctbreedBatchName);
    }
    //查询供方猪场信息
    const _queryFarmName = (id, json) => {
        ReceivepigApi.queryBaseOrgunitList(id, 1, '210').then(res => {
            let _farm = [];
            $('#farmName').select2({
                placeholder: '请选择供方猪场...', //默认文字提示
                language: "zh-CN",//汉化
                allowClear: true,//允许清空
                tags: true,
                data: res.map(item => {
                    _farm = res;
                    return {
                        ...item,
                        id: item.id,
                        text: `${item.name}(${item.numCode})`,
                        name: item.name
                    }
                })
            });
            $('#farmName').setSelectValue();
            if (json) {
                $('#farmName').setSelectValue(_farm.find(s => s.name == json)?.id, json);
            }
        });
    }
    // 保存分录以上的内容
    const storeSession = () => {
        const propertiesToCopy = [
            'bizDate', 'supplierId', 'supplierName', 'supplierNumCode', 'farmOrgUnitName',
            'suppBreedBatchName', 'totalCount', 'totalWeight', 'totalPrice', 'totalSuupLossCount',
            'totalBuyLossCount', 'entryDays', 'shipAddress', 'shipRegion', 'fiOrgUnitId',
            'fiOrgUnitName', 'serviceDepartmentId', 'serviceDepartmentName', 'remark'
        ];
        const deliverDatas = propertiesToCopy.reduce((obj, prop) => {
            obj[prop] = _vm[prop];
            return obj;
        }, {});
        if ($('#selctFarm').css('display') == 'block') {
            deliverDatas.selctFarmName = $('#farmName').select2('data')[0]?.name || $('#farmName').select2('data')[0]?.text
        }
        if ($('#selctbreedBatch').css('display') == 'block') {
            deliverDatas.selctbreedBatchName = $('#breedBatch').select2('data')[0]?.name || $('#breedBatch').select2('data')[0]?.text
        }
        // 保存数据内容
        Utils.SetRouterState('deliverDatas', deliverDatas)
    }

    // 日期选择器
    const pick = () => {
        weui.datePicker({
            defaultValue: (moment(new Date()).format('YYYY-MM-DD')).split('-'),
            end: moment(new Date()).format('YYYY-MM-DD'),
            className: 'mypick',
            onConfirm: async function (result) {
                let value = `${result[0].value}-${result[1].value}-${result[2].value}`;
                _vm.bizDate = moment(new Date(value)).format('YYYY-MM-DD')
            }
        });// 默认配置
    }

    // 服务部
    const _serviceDepartment = (id, json) => {
        ReceivepigApi.queryBaseOrgunitList(id, 1, 210).then(res => {
            $("#farmOrg").empty().select2({
                placeholder: '请选择服务部...',//默认文字提示
                language: "zh-CN",//汉化
                allowClear: true,
                data: res.map(item => {
                    return {
                        id: item.id,
                        numCode: item.numCode,
                        text: `${item.name}(${item.numCode})`,
                        name: item.name
                    }
                }),
            });
            $(`#farmOrg`).setSelectValue()
            if (json) {
                $(`#farmOrg`).setSelectValue(json.serviceDepartmentId, json.serviceDepartmentName)
                _vm.serviceDepartmentId = json.serviceDepartmentId
                _vm.serviceDepartmentName = json.serviceDepartmentName
            }
        });
    }

    // 获取父级
    const getAllParend = (id, data) => {
        var res = [];    //定义一个数组用来存放找到的所有父级
        function dg(p) {
            for (var i = 0; i < data.length; i++) {
                var obj = data[i];
                if (obj.oId == p) {
                    //将找到的父级元素放到res中
                    res.push(obj);
                    dg(obj.poId);
                }
            }
        }
        dg(id);
        return res;    //返回找到的数据
    }

    // 操作函数
    const clickFun = () => {
        //取消按钮，返回列表
        $(document).on('click', '#returnMain', function () {
            window.sessionStorage.removeItem("getEntryInfo");
            window.sessionStorage.removeItem("deliverDatas");
            window.sessionStorage.removeItem("ids");
            location.href = `../receivepig/receivepiglist.html?v=${Utils.GetTime()}`;
        });

        //取消，关闭弹框
        $(document).on('click', '#returnAddSaleOrders', function () {
            $('#pop').css('display', 'none');
            $('.show-box').css('display', 'none');
            $('.show-box').css({
                'bottom': '-6rem',
                'transition': 'all .ls ease-in'
            });
        });

        // 点击分录
        $('#add-saleEntry').on("click", function (e) {
            if (!Utils.IsNotNull(_vm.fiOrgUnitId)) {
                $.toptip(`请先选择公司!`, 'warning');
                return
            }
            if (!Utils.IsNotNull(_vm.serviceDepartmentId)) {
                $.toptip(`请先选择服务部!`, 'warning');
                return
            }
            // 存储数据
            storeSession()
            let index = JSON.parse(Utils.GetSessionStorage("getEntryInfo"))?.length || 0
            location.href = `../receivepig/receivepigentry.html?v=${Utils.GetTime()}&sdit=${_vm.serviceDepartmentId}&index=${index}&isEdit=${false}`;
        })

        // 提交数据
        $('#informationSubmit').on("click", function (e) {
            let entries = JSON.parse(Utils.GetSessionStorage("getEntryInfo"))
            if (!Utils.IsNotNull(_vm.fiOrgUnitId)) {
                return $.toptip(`请选择公司!`, 'warning');
            }
            if (!Utils.IsNotNull(_vm.serviceDepartmentId)) {
                return $.toptip(`请选择服务部!`, 'warning');
            }
            if (!Utils.IsNotNull(_vm.supplierId)) {
                return $.toptip(`请选择供应商!`, 'warning');
            }
            if ($('#selctFarm').css('display') == 'block') {
                let farmNameId = $('#farmName').select2('data')[0]?.id
                if (!Utils.IsNotNull(farmNameId)) {
                    return $.toptip(`请选择供方猪场!`, 'warning');
                }
            }
            if ($('#selctbreedBatch').css('display') == 'block') {
                let breedBatchId = $('#breedBatch').select2('data')[0]?.id
                if (!Utils.IsNotNull(breedBatchId)) {
                    return $.toptip(`请选择供方批次!`, 'warning');
                }
            }
            if (!Utils.IsNotNull(_vm.totalPrice)) {
                return $.toptip(`请输入总价!`, 'warning');
            }
            if (_vm.totalSuupLossCount === '' || _vm.totalSuupLossCount === 'undefined') {
                return $.toptip(`请输入供方总损耗数量!`, 'warning');
            }
            if (!Utils.IsNotNull(_vm.entryDays)) {
                return $.toptip(`请输入猪只日龄!`, 'warning');
            }
            if (!Utils.IsNotNull(_vm.shipRegion)) {
                return $.toptip(`请选择发货行政区划!`, 'warning');
            }
            if (!Utils.IsNotNull(_vm.shipAddress)) {
                return $.toptip(`请输入详细地址!`, 'warning');
            }
            var reg = /^(?!0+(?:\.0+)?$)(?:[1-9]\d*|0)(?:\.\d{1,2})?$/
            if (!(reg.test(_vm.totalPrice))) return $.toptip(`总价必须大于0并且只能保留两位小数`, 'warning')

            if (!(/^[1-9]\d*$|^0$/.test(_vm.totalSuupLossCount))) {
                return $.toptip(`供方总损耗数量必须为大于等于0的整数!`, 'warning');
            }
            if (!Utils.IsNotNull(entries)) {
                return $.toptip(`请添加接苗单分录信息!`, 'warning');
            }
            savetips();
        })

        // 删除分录
        $(document).on('click', '#salesEntry div[data-flag=table-click-delete]', function () {
            let seq = $(this).data('index')
            $.modal({
                autoClose: false,
                title: '删除提示',
                text: `<div class="weui-cells__group weui-cells__group_form" style="margin-top:-5px">
					<div class="" style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;">
						<div>是否确认删除该分录?</div>
					</div>`,
                buttons: [
                    {
                        text: "取消", className: "default", onClick: function () {
                            $.closeModal();
                        }
                    },
                    {
                        text: "确定", onClick: function () {
                            // 过滤
                            let datas = getEntryInfo.filter(item => item.seq != seq)
                            // 重置seq
                            let info = datas.map((item, index) => {
                                item.seq = index
                                return item
                            }) || []

                            // 赋值 
                            JSON.stringify(Utils.SetSessionStorage("getEntryInfo", info))
                            $('#salesEntry').empty().append(addsaleTemplate(info));

                            let _netWeight = [], _count = [], _buyLossCount = [];
                            $.each(info, function (i, v) {
                                _netWeight.push(Number(v.netWeight));
                                _count.push(parseInt(v.count));
                                _buyLossCount.push(parseInt(v.buyLossCount));
                            });

                            let netWeight = eval(_netWeight?.join('+'));
                            let count = eval(_count?.join('+'));
                            let buyLossCount = eval(_buyLossCount?.join('+'));
                            _vm.totalWeight = netWeight || 0
                            _vm.totalCount = count || 0
                            _vm.totalBuyLossCount = buyLossCount || 0
                            _vm.newtotalCount = count + buyLossCount || 0
                            $.closeModal();
                        }
                    }
                ]
            });
        });

        // 编辑
        $(document).on('click', '#salesEntry div[data-flag=table-click-edit]', function () {
            // 存储数据
            storeSession()
            // 获取分录 否则 默认是0
            let index = $(this).data('index')
            location.href = `../receivepig/receivepigentry.html?v=${Utils.GetTime()}&sdit=${_vm.serviceDepartmentId}&index=${index}&isEdit=${true}`;
        });
    }

    // 初始化发货行政区划
    const _initcityPicker = () => {
        // 取消按钮
        $('#canvalBtn').on('click', function () {
            $('#maskback').css('display', 'none')
            // $('body').removeClass('disablemask')
            document.body.style.overflow = 'scroll'
            document.body.style.position = 'relative'
            // $("html,body").stop().animate({
            //     scrollTop: $("body").height()
            // }, 300);

        })
        // 确定按钮
        $('#determineBtn').on('click', function () {
            let selectArr = []
            $('#selectCity').find('.innerAddress').each((index, item) => {
                let selectAddresss = $(item).text()
                if (Utils.IsNotNull(selectAddresss) && selectAddresss != '请选择') {
                    selectArr.push(selectAddresss)
                }
            })

            let selectIdArr = []
            $('#selectCity').find('.adressId').each((index, item) => {
                let selectAddresssId = $(item).text()
                if (Utils.IsNotNull(selectAddresssId)) {
                    selectIdArr.push(selectAddresssId)
                }
            })
            _vm.shipRegion = `${selectIdArr.join(';')}|${selectArr.join(';')}`
            let selectCity = selectArr.join('-')

            $('#intentionCity').val(selectCity)
            editintentionCity = selectCity
            if (!Utils.IsNotNull(selectArr[0])) {
                $.toptip(`请选择省!`, 'warning');
                return
            }
            else if (!Utils.IsNotNull(selectArr[1])) {
                $.toptip(`请选择市!`, 'warning');
                return
            }
            else if (!Utils.IsNotNull(selectArr[2])) {
                $.toptip(`请选择区县!`, 'warning');
                return
            }
            else {
                $('#canvalBtn').click()
            }

        })
        // 点击灰色遮罩层
        $('#unimportmask').on('click', function () {
            $('#canvalBtn').click()
        })
        // 点击发货行政区划
        $('#search-intentionCity').on('click', function () {
            editintentionCity = $('#intentionCity').val() || []
            // 关闭键盘
            document.activeElement.blur();
            // body禁止滚动
            document.body.style.position = 'fixed'
            document.body.style.overflow = 'hidden'
            // 清空选择页面内容
            $('#intentionContain').children('div').eq(0).empty()
            $('.innerAddress,.adressId').text('')
            changeStyle(0)

            addressindex = 0
            getAddress('province', "e8wa").then(res => {
                if (Utils.IsNotNull(editintentionCity)) {
                    editintentionArr = editintentionCity.split('-')
                    let editaddress = res.filter(item => {
                        return item.name == editintentionArr[0]
                    })
                    if (Utils.IsNotNull(editaddress)) {
                        $(`#${editaddress[0].id}`).click()
                    }
                }
            })
            setTimeout(() => {
                $('#maskback').css('display', 'block')
            }, 200);
        })
        // 点击导航栏
        $('#selectCity').on('click', 'li', function () {
            editintentionArr = []
            $(this).addClass('activeStyle').siblings('li').removeClass('activeStyle')
            $(this).find('.uderline').addClass('underlineit')
            $(this).siblings('li').find('.uderline').removeClass('underlineit')
            addressindex = $(this).index()
            $('#intentionContain').children('div').eq(addressindex).css('display', 'block').siblings('div').css('display', 'none')
        })
        // 选择之后
        $(document).on('click', '.addressCon', async function () {
            let addressid = $(this).attr('id')
            let addressName = $(this).text()
            $('#selectCity').find('li').eq(addressindex).find('span').text(addressName)
            $('#selectCity').find('li').eq(addressindex).find('.adressId').text(addressid)

            $(this).addClass('activeStyle').siblings('div').removeClass('activeStyle')
            addressindex = addressindex + 1
            changeStyle(addressindex)
            $('#intentionContain').children('div').eq(addressindex).empty()
            $('#intentionContain').children('div').eq(addressindex).last().nextAll().empty()
            $('#selectCity').find('li').eq(addressindex).find('span').parent().last().nextAll().find('.innerAddress').text('')
            if (addressindex == 1) {
                getAddress('city', addressid).then(res => {
                    if (Utils.IsNotNull(editintentionArr) && Utils.IsNotNull(editintentionArr[1])) {
                        let editaddress = res.filter(item => {
                            return item.name == editintentionArr[1]
                        })
                        if (Utils.IsNotNull(editaddress)) {
                            $(`#${editaddress[0].id}`).click()
                        }
                    }
                })
                let nextNav = $('#selectCity').find('li').eq(addressindex + 1).find('span')
                if (Utils.IsNotNull(nextNav.text())) {
                    nextNav.text('')
                }
            }
            else if (addressindex == 2) {
                getAddress('district', addressid).then(res => {
                    if (Utils.IsNotNull(editintentionArr) && Utils.IsNotNull(editintentionArr[2])) {
                        let editaddress = res.filter(item => {
                            return item.name == editintentionArr[2]
                        })
                        if (Utils.IsNotNull(editaddress)) {
                            $(`#${editaddress[0].id}`).click()
                        }
                    }
                })
            }
            else if (addressindex == 3) {
                getAddress('street', addressid).then(res => {
                    if (Utils.IsNotNull(editintentionArr) && Utils.IsNotNull(editintentionArr[2])) {
                        let editaddress = res.filter(item => {
                            return item.name == editintentionArr[3]
                        })
                        if (Utils.IsNotNull(editaddress)) {
                            $(`#${editaddress[0].id}`).click()
                        }
                    }
                })
            }
            else if (addressindex > 3) {
                $('#selectCity').find('li').eq(3).find('span').text(addressName)
            }
        })
    }
    const changeStyle = (id) => {
        $('#selectCity').find('li').eq(id).find('span').text('请选择')
        $('#selectCity').find('li').eq(id).addClass('activeStyle').siblings('li').removeClass('activeStyle')
        $('#selectCity').find('li').eq(id).find('.uderline').addClass('underlineit')
        $('#selectCity').find('li').eq(id).siblings('li').find('.uderline').removeClass('underlineit')
    }
    // 获取地点 联动
    const getAddress = async (level, pid) => {
        return new Promise((resolve, reject) => {
            let addressQuery = {
                level: level,
                pid: pid
            }
            getDistory(addressQuery).then(res => {
                let addressData
                if (addressindex == 0) {
                    addressData = [...res]
                }
                else {
                    addressData = [...res]
                }
                $('#intentionContain').children('div').eq(addressindex).css('display', 'block').siblings('div').css('display', 'none')
                addressData.forEach(item => {
                    $('#intentionContain').children('div').eq(addressindex).append(`<div class="addressCon" id="${item.id}" style="margin-bottom:8px">${item.name}</div>`)
                })
                resolve(addressData)
            })
        })
    }

    //获取行政区划 
    const getDistory = (data) => {
        return new Promise((resolve, reject) => {
            $.ajax({
                "url": `${Utils.CurDomain.SubDataUrl}/districts/q?l=${data.level}&pid=${data.pid}`,
                "type": 'GET',
                "dataType": "json",
                "beforeSend": Utils.AjaxBeforeSend,
                "success": function (result) {
                    resolve(result.data)
                },
                "error": function (xhr, textStatus, errorThrown) {
                    Utils.AjaxError(xhr, textStatus, errorThrown)
                }
            });
        })
    }
    // 保存
    const savetips = () => {
        $.modal({
            autoClose: false,
            title: '提示',
            text: `<div class="weui-cells__group weui-cells__group_form" style = "margin-top:-5px" >
                    <div class="addedientry" style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;">
                        <div class="addentry" >是否确认保存该接苗单？</div >
                    </div > 
                    </div > `,
            buttons: [
                {
                    text: "取消", className: "default", onClick: function () {
                        $.closeModal();
                    }
                },
                {
                    text: "保存", onClick: function () {
                        $.closeModal();
                        let ids = Utils.GetSessionStorage("ids")
                        let entries = JSON.parse(Utils.GetSessionStorage("getEntryInfo"))

                        const propertiesToCopy = [
                            'bizDate', 'supplierId', 'supplierName', 'supplierNumCode', 'farmOrgUnitName',
                            'suppBreedBatchName', 'totalCount', 'totalWeight', 'totalPrice', 'totalSuupLossCount',
                            'totalBuyLossCount', 'entryDays', 'shipAddress', 'shipRegion', 'fiOrgUnitId',
                            'fiOrgUnitName', 'serviceDepartmentId', 'serviceDepartmentName', 'remark'
                        ];
                        const datas = propertiesToCopy.reduce((obj, prop) => {
                            obj[prop] = _vm[prop];
                            return obj;
                        }, {});
                        if ($('#selctFarm').css('display') == 'block') {
                            datas.farmOrgUnitName = $('#farmName').select2('data')[0]?.name || $('#farmName').select2('data')[0]?.text
                        }
                        if ($('#selctbreedBatch').css('display') == 'block') {
                            datas.suppBreedBatchName = $('#breedBatch').select2('data')[0]?.name || $('#breedBatch').select2('data')[0]?.text
                        }
                        entries.forEach(item => {
                            let imageArr = []
                            if (Utils.IsNotNull(item.attachesStr)) {
                                item.attachesStr.forEach(item1 => {
                                    imageArr.push(item1.imageId)
                                })
                                item.attaches = imageArr.join(',')
                            }
                        })



                        let addJson = { ...datas, entreis: [...entries] }

                        if (Utils.IsNotNull(ids)) {
                            return ReceivepigApi.putReceivePigBill(ids, JSON.stringify(addJson)).then(res => {
                                $.toptip('请求成功。', 'success');
                                // 延时一秒跳转  要看提示 
                                setTimeout(function () {
                                    window.sessionStorage.removeItem("getEntryInfo");
                                    window.sessionStorage.removeItem("deliverDatas");
                                    window.sessionStorage.removeItem("ids");
                                    location.href = `../receivepig/receivepiglist.html?v = ${Utils.GetTime()} `;
                                }, 1000);
                            })
                        }
                        else {
                            ReceivepigApi.postReceivePigBill(JSON.stringify(addJson)).then(res => {
                                $.toptip('请求成功。', 'success');
                                // 延时一秒跳转  要看提示 
                                setTimeout(function () {
                                    window.sessionStorage.removeItem("getEntryInfo");
                                    window.sessionStorage.removeItem("deliverDatas");
                                    location.href = `../receivepig/receivepiglist.html?v = ${Utils.GetTime()} `;
                                }, 1000);
                            }, err => {
                                $.toptip(err.responseJSON?.msg, 'error');
                            });
                        }
                    }
                }
            ]
        });
    }

    // 获取地址栏的 参数 
    const getUrlKey = (name) => {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    }
    //解决字段过长问题
    const cutstr = (str, len) => {
        var str_length = 0;
        var str_len = 0;
        var str_cut = new String();
        str_len = str.length;
        for (var i = 0; i < str_len; i++) {
            var a = str.charAt(i);
            str_length++;
            if (escape(a).length > 4) {
                //中文字符的长度经编码之后大于4 
                str_length++;
            }
            str_cut = str_cut.concat(a);
            if (str_length >= len) {
                str_cut = str_cut.concat("...");
                return str_cut;
            }
        }
        //如果给定字符串小于指定长度，则返回源字符串； 
        if (str_length < len) {
            return str;
        }
    }
})(window, document, jQuery)